﻿using Common;
using Entity.Customer;
using Entity.Request;
using Entity.ResultModel.UserInfo;
using IHotelBLL;
using IHotelDAL;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HotelBLL
{
    public class UserInfoBLL : IUserInfoBLL
    {
        IUserInfoDAL _userInfoDAL;
        public UserInfoBLL(IUserInfoDAL userInfoDAL)
        {
            _userInfoDAL = userInfoDAL;
        }
        /// <summary>
        /// 获取用户列表数据接口
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<GetUserInfosModel> GetUserInfos(int page, int limit, out int count)
        {
            IQueryable<CustomerInfo> dbUserInfos = _userInfoDAL.GetEntities().Where(u => u.Name =="");
            //获取数据库所有用户的数量
            count = dbUserInfos.Count();    
            //分页
            var userInfos = dbUserInfos.Skip((page - 1) * limit).Take(limit).Select(u => new
            {

                u.Id,
                u.Name,
                u.Phone,
                u.Sex,
                u.CreateTime
            }).ToList();
            var tempList = userInfos.Select(u =>
            {
                string sexStr = u.Sex;
                string dateTimeStr = u.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                return new GetUserInfosModel
                {
                    Id = u.Id,
                    UserName = u.Name,
                    Phone = u.Phone,
                    Sex = u.Sex,
                    CreateTime = dateTimeStr
                };
            }).ToList();
            return tempList;
        }
        /// <summary>
        /// 添加用户接口BLL
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="phone"></param>
        /// <param name="passWord"></param>
        /// <param name="sex"></param>
        /// <param name="age"></param>
        /// <param name="address"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool Register(CustomerInfo customer, out string msg)
        {
            //通过手机号获取用户信息
            CustomerInfo customerInfo = _userInfoDAL.GetEntities().Where(c => c.Phone == customer.Phone || c.ID_Card == customer.ID_Card).FirstOrDefault();
            if (customerInfo != null)
            {
                msg = "用户已注册";
                return false;
            }
            if (!Verification(customer.ID_Card) || !Verification(customer.Phone))
            {
                msg = "身份证或手机号码有误";
                return false;
            }
            customer.CreateTime = DateTime.Now;
            //使用MD5 加密密码
            customer.PassWord = MD5Helper.MD5Encrypt64(customer.PassWord);
            //创建用户对象
            customer.Id = Guid.NewGuid().ToString();
            bool isSuccess = _userInfoDAL.CreateEntity(customer);
            //三目运算符
            msg = isSuccess ? "创建成功" : "创建失败";
            return isSuccess;
        }
        /// <summary>
        /// 修改用户接口
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userName"></param>
        /// <param name="sex"></param>
        /// <param name="phone"></param>
        /// <param name="address"></param>
        /// <param name="age"></param>
        /// <param name="passWord"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateUserInfo(CustomerInfo customer, out string msg)
        {
            CustomerInfo customerInfo = GetUserInfoById(customer.Id);
            if (customerInfo ==null)
            {
                msg = "未找到用户";
                return false;
            }
            bool isSuccess = _userInfoDAL.UpdateEntity(customer);
            msg = isSuccess ? "修改成功" : "修改失败";
            return isSuccess;
        }
        /// <summary>
        /// 根据Id用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CustomerInfo GetUserInfoById(string id)
        {
            return _userInfoDAL.GetEntities().FirstOrDefault(u => u.Id == id);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool DeleteUserInfo(string id, out string msg)
        {

            //获取用户信息
            CustomerInfo customerInfo = _userInfoDAL.GetEntities().FirstOrDefault(u => u.Id == id);
            if (customerInfo == null)
            {
                msg = "删除用户不存在";
                return false;
            }
            //真删除
            bool isSuccess = _userInfoDAL.DeleteEntity(customerInfo);
            msg = isSuccess ? "删除成功" : "删除失败";
            return isSuccess;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public CustomerInfo Login(UserLogin login,out string msg)
        {
            login.Password = MD5Helper.MD5Encrypt64(login.Password);
           var User = _userInfoDAL.GetEntities().Where(u => (u.Phone == login.UserName || u.ID_Card == login.UserName )&& u.PassWord == login.Password).FirstOrDefault();
            if (User == null)
            {
                msg = "用户名或密码有误";
                return null;
            }
            msg = "登录成功";
            return User;
        }
        /// <summary>
        /// 用户名校验
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public bool Verification(string UserName)
        {
            bool isuccess = false;
            if (UserName.Length==11)
            {
               return  ValidateMobile(UserName);
            }
            else
            if (UserName.Length == 18)
            {
               return CheckIDCard18(UserName);
            }
            return isuccess;
        }
        public bool ValidateMobile(string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
                return false;
            return Regex.IsMatch(mobile, @"^(13|14|15|16|18|19|17)\d{9}$");
        }
        private bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
                || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证  
            }
            return true;//符合GB11643-1999标准  
        }

        public object GetUserInfoDetail(string userId)
        {
            var userInfo = _userInfoDAL.GetEntities().FirstOrDefault(u => u.Id == userId);
            return userInfo;
        }
    }
}



